package com.icode.web.startup;

import com.icode.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * User: alexz
 * Date: 15-1-20
 * Time: 上午10:22
 */
@Configuration
@Order(2)
public class BackendWebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/public/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().requestMatchers()
                .antMatchers("/back/**", "/exit")
                .and().exceptionHandling().accessDeniedPage("/deny")
                .and()
                .sessionManagement().maximumSessions(1)
                .and().and()
                .authorizeRequests()
                .antMatchers("/back/welcome").access("isAuthenticated() and principal.isAdministrator()")
                .anyRequest().access("isAuthenticated() and principal.isAdministrator()")
                .and()
                .formLogin()
                .loginPage("/back/login")
                .permitAll()
                .defaultSuccessUrl("/back/welcome")
                .and()
                .logout()
                .logoutUrl("/exit")
                .logoutSuccessUrl("/back/login");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder);
    }
}
